<?php

class Weibo {
    
    private $_error;
    private $appid;
    private $appsecret;

    public function __construct() {
        $this->appid = Configure::get('weibo.appid');
        $this->appsecret = Configure::get('weibo.appsecret');
    }

    public function getAppId() {
        return $this->appid;
    }
    
    public function getOpenid($access_token) {
        if(!$access_token) {
            $this->_error = 'access_token获取失败,登录失败';
            return false;
        }
        $url = 'https://api.weibo.com/2/account/get_uid.json';
        $result = Curl::get($url, array('access_token'=>$access_token));
        $result = json_decode($result, true);
        if(isset($result['uid'])) {
            return $result['uid'];
        }
        $this->_error = '获取uid失败,请重新登录';
        return false;
    }
    
    public function getUserInfo($access_token, $openid) {
        $url = 'https://api.weibo.com/2/users/show.json';
        $data = [
            'access_token' => $access_token,
            'uid' => $openid
        ];
        $result = Curl::get($url, $data);
        $result = json_decode($result, true);
        if(!isset($result['error_code']) || $result['error_code'] == 0){
            $user_info = [
                'openid' => $openid,
                'nickname' => $result['name'],
                'avatar' => $result['avatar_large'],
                'sex' => $result['gender']=='m'?1:($result['gender']=='f'?2:0)
            ];
            return $user_info;
        }
        $this->_error='获取用户信息失败,请稍后重试';
        return false;
    }
    
    public function getError() {
        return $this->_error;
    }
}